﻿using System.Globalization;
using System.Windows.Controls;

namespace SessionHunter.Business.Validators
{
    /// <summary>
    /// Validates the lengths of strings in controls, usually TextBoxes
    /// </summary>
    /// <remarks>
    /// From http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation
    /// </remarks>
    public class StringRangeValidationRule : ValidationRule
    {
        private int _minimumLength = -1;
        private int _maximumLength = -1;
        private string _errorMessage;

        /// <summary>
        /// Gets or sets the minimum length for the control.
        /// </summary>
        /// <value>
        /// The minimum length.
        /// </value>
        public int MinimumLength
        {
            get { return _minimumLength; }
            set { _minimumLength = value; }
        }

        /// <summary>
        /// Gets or sets the maximum length for the control.
        /// </summary>
        /// <value>
        /// The maximum length.
        /// </value>
        public int MaximumLength
        {
            get { return _maximumLength; }
            set { _maximumLength = value; }
        }

        /// <summary>
        /// Gets or sets the error message to display if there is an issue.
        /// </summary>
        /// <value>
        /// The error message.
        /// </value>
        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { _errorMessage = value; }
        }

        /// <summary>
        /// Performs validation checks on a value.
        /// </summary>
        /// <param name="value">The value from the binding target to check.</param>
        /// <param name="cultureInfo">The culture to use in this rule.</param>
        /// <returns>
        /// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
        /// </returns>
        public override ValidationResult Validate(object value,
            CultureInfo cultureInfo)
        {
            ValidationResult result = new ValidationResult(true, null);
            string inputString = (value ?? string.Empty).ToString();
            if (inputString.Length < this.MinimumLength ||
                   (this.MaximumLength > 0 &&
                    inputString.Length > this.MaximumLength))
            {
                result = new ValidationResult(false, Resources.Strings.ResourceManager.GetString(this.ErrorMessage));
            }
            return result;
        }
    }
}
